load "./lib/web_page_craw.rb"

class MusicsController < ApplicationController
  def new
    @music = Music.new()
  end

  def show
    @test1=justTest
    @music=Music.find(params[:id])
    @extend_info=fetch_doubanMusicApi(@music.douban_id)

    @download_url = @music.download_urls.build


  end
  def edit

  end

  def search
  end

  def getMusicInfo_thoughDouban(doubanID)


    hashObj=fetch_doubanMusicApi(doubanID)

    if hashObj.nil?
      return nil
    else
      music =Music.new
      music.album_name=hashObj["title"]
      music.artist_name=hashObj["author"].map{|e| e["name"]}.join("/")
      music.logo_url=hashObj["image"]
      music.douban_id= doubanID
      return music
    end

  end

  def create

       # Not the final implementation!
    doubanID=music_params[:douban_id]

    unless (doubanID.blank?)
      @music =getMusicInfo_thoughDouban(doubanID)

    end
    @music ||= Music.new(music_params)


    if @music.save

      flash[:success] = "成功创建#{@music.album_name}"
      redirect_to @music
    else
      render 'new'
    end

  end

  def destroy
    Music.find(params[:id]).destroy
    flash[:success] = "音乐已删除."
    redirect_to musics_url
  end

  def index
    @musics = Music.paginate(page: params[:page],per_page:3)
  end

  def search
    query_name ="%#{params[:search]}%"
    @musics = Music.where("album_name like :album_name or artist_name like :artist_name",
    {album_name: query_name, artist_name:query_name})
    .paginate(page: params[:page],per_page:3)

    render 'search_result'
  end

  def update

    if @user.update_attributes(user_params)
      flash[:success] = "资料已更新"
      redirect_to @user
    else
      render 'edit'
    end
  end



  private

  def music_params
    params.require(:music).permit(:album_name, :artist_name,:douban_id)
  end

end